/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.gui;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
/**
 *
 * @author Ugo
 */
@Named(value = "signinBean")
@RequestScoped
public class SigninBean {

    private String username;
    private String password;
    
    public SigninBean() {
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.username, this.password);
        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"","Login failed."));
            return "login";
        }
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"","Welcome back."));
        return "/user/home?faces-redirect=true";
    }

    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.logout();
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("scheduleBean", null);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("menuBean", null);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("notificationBean", null);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("notificationCheckBean", null);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userBean", null);
          //  FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("expimpBean", null);

        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"","Logout failed."));
        }
        return "/login?faces-redirect=true";
    }
}

